import { h, render } from 'vue'
import XtxMessage from './message.vue'

type Props = {
  type: 'success' | 'error' | 'warning'
  text: string
  duration?: number
}
// Message({type: 'success', text: 'Hello'})

const oDiv = document.createElement('div')
oDiv.className = 'tk'
document.body.appendChild(oDiv)

// #1
let timer = -1

export default function Message({ type, text, duration = 2000 }: Props) {
  // 参数：组件、组件的 props 属性列表
  const vNode = h(XtxMessage, { type, text })
  render(vNode, oDiv)

  // #2 防止重复点击开启多个定时器
  clearInterval(timer)

  // #3 开启定时器
  timer = window.setTimeout(() => {
    render(null, oDiv)
  }, duration)
}
Message.error = function (text: string, duration = 2000) {
  Message({
    type: 'error',
    text,
    duration,
  })
}
Message.success = function (text: string, duration = 2000) {
  Message({
    type: 'success',
    text,
    duration,
  })
}
Message.warning = function (text: string, duration = 2000) {
  Message({
    type: 'warning',
    text,
    duration,
  })
}
